package main

import (
	"fmt"
	"log"

	"os"

	"golang.org/x/net/websocket"
)

const buflen int = 512

func read(conn *websocket.Conn) {
	msg := make([]byte, buflen)
	for {
		n, err := conn.Read(msg)
		if err != nil {
			fmt.Println("error:", err.Error())
			return
		}
		fmt.Println("receive:", string(msg[:n]))
	}
}
func client() {
	fmt.Println("ID:", os.Args[1])
	conn, err := websocket.Dial("ws://127.0.0.1:8080/echo?userID="+os.Args[1], "", "http://localhost/")
	if err != nil {
		fmt.Println("error:", err.Error())
		return
	}
	go read(conn)
	msg := make([]byte, buflen)
	for {
		n, err := fmt.Scan(&msg)
		if err != nil {
			log.Fatal(err)
		}
		if n == 0 {
			fmt.Println("error:no input")
			continue
		}
		n, err = conn.Write(msg)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Send: %s\n", msg[:n])
	}
}
func main() {
	client()
}
